#include <iostream>
#include <fstream>
#include "contact.pb.h"
using namespace std;
using namespace contacts;
void AddPeopleInfo(PeopleInfo *people_info_ptr)
{
    cout << "-------------新增联系人-------------" << endl;
    cout << "请输入联系人姓名: ";
    string name;
    getline(cin, name);
    people_info_ptr->set_name(name);//输入用set_函数
    cout << "请输入联系人年龄: ";
    int age;
    cin >> age;
    people_info_ptr->set_age(age);
    cin.ignore(256, '\n');
    for (int i = 1;; i++)
    {
        cout << "请输入联系人电话" << i << "(只输入回车完成电话新增): ";
        string number;
        getline(cin, number);
        if (number.empty())
        {
            break;
        }
        //number需要添加才可以用
        PeopleInfo_Phone*  phone=people_info_ptr->add_phone();
        phone->set_number(number);
    }
    cout << "-----------添加联系人成功-----------" << endl;
}

int main()
{

    Contacts contacts;
    // 先读取已存在的 contacts
    fstream input("text.bin",ios::in | ios::binary);
    if (!input)//是否存在
    {
        cout << ": File not found. Creating a new file." << endl;
    }
    else if (!contacts.ParseFromIstream(&input))//反序列化
    {
        cerr << "Failed to parse contacts." << endl;
        input.close();
        return -1;
    }
    // 新增一个联系人
    AddPeopleInfo(contacts.add_contacts());
    //向磁盘文件写入新的 contacts
    fstream output("text.bin",ios::out | ios::trunc | ios::binary);
    if (!contacts.SerializeToOstream(&output))//序列化
    {
        cerr << "Failed to write contacts." << endl;
        input.close();
        output.close();
        return -1;
    }
    input.close();
    output.close();
    return 0;
}